package com.romotc.qqrobot.webqq.qqInterfaceCatching;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.romotc.joyin.bean.Customer;
import com.romotc.joyin.bean.CustomerService;
import com.romotc.qqrobot.bean.QQLogedin;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Search_qq_by_uin2_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.DateProcessor;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.Search_qq_by_uin2_Processor;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.UiOptionDateProcessor;
import com.romotc.scache.RequestSpy;
import com.romotc.scache.WebConnection;
/**
 * 如果请求的uin为负数则发回一小段js代码
 * @author Administrator
 *
 */
public class Get_single_long_nick2_Catching extends QQUrlCatchingInterface {

	@Override
	public boolean modifyResponse(WebConnection wc, RequestSpy rqSpy)
			throws IOException {
		return false;
		
	}


	@Override
	public boolean hackRequest(RequestSpy requestSpy) {
		JSONObject jsonReqInfo = requestSpy.getReqInfoJson();
		long uin;
		try {
			uin = jsonReqInfo.getLong("tuin");
			if(uin < 0) {
				//make_headers(200, "message/http", null, null, -1, 0, 0, null);
				//找出uin 绝对值对应的客户 取得客户的Qq号码
				long custId = -uin;
				Customer cust = CustomerService.qryCustomerById(custId);
				byte[] b = new byte[0];
				//应该不会出现为空的这种情况
				if(cust != null && StringUtils.isNotBlank(cust.getQqNum())) {
					
					//根据QQ号码调用腾讯接口获取Uin等信息
					QQLogedin curLoginQQ = getCurQqLogedIn(requestSpy);
					if(curLoginQQ != null) {
						//processor 内部将数据存数据库，然后将需要返回给界面的信息保存在result2UI的属性中
						UiOptionDateProcessor processor = new Search_qq_by_uin2_Processor();
						
						//RomUnDo 以后再增加这部分功能
						Search_qq_by_uin2_InterCall.getInstance()
											.call(curLoginQQ, new JSONObject(), processor);
						
						//返回js代码修改界面响应元素的id和uin属性 + 触发头像的onMouseOver事件重新调用腾讯long_nick 和level等信息
						String javascript = processor.execJavascript(uin);//"javascript:alert('12d中美国华文');";
						b = javascript.getBytes("utf-8");
					}
				}

				ByteArrayInputStream bis = new ByteArrayInputStream(b);
				DataInputStream dis = new DataInputStream(bis);
				requestSpy.make_headers(200, null, null, null, b.length, new Date()
					.getTime(), 0, null);
				
				requestSpy.send_headers();
				WebConnection wc = new WebConnection(dis);
				requestSpy.transfer_object(wc, null, null);
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

}
